﻿using System;
using System.Runtime.InteropServices;
using System.Drawing;

namespace DesktopCapture
{
    class DCapture
    {
        [DllImport("user32.dll", SetLastError = false)]
        static extern IntPtr GetDesktopWindow();

        [DllImport("user32.dll")]
        static extern IntPtr GetDC(IntPtr hWnd);

        [DllImport("gdi32.dll")]
        static extern IntPtr GetCurrentObject(IntPtr hdc, uint uObjectType);

        [DllImport("user32.dll")]
        static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDC);

        const int OBJECT_BITMAP = 7;

        public static Bitmap Capture()
        {
            // Get Device Context
            IntPtr desktopWindow = GetDesktopWindow();
            IntPtr desktopDC = GetDC(desktopWindow);
            // Get GDI handle of image
            IntPtr desktopBitmap = GetCurrentObject(desktopDC, OBJECT_BITMAP);
            // Create .Net Image object
            Bitmap desktopImage = Image.FromHbitmap(desktopBitmap);
            // Realease Device Context, return desktop Image
            ReleaseDC(desktopWindow, desktopDC);
            return desktopImage;
        }
    }
}
